<?php
/**
 * 处理用户的评测请求
 *
 * @todo
 * @author Judas <judasnow@gmail.com>
 * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
 */
session_start();
require_once('path.php');
require_once( SOJ_ROOT.'/include/function/lib.php');

@$request = $_GET;

try{

	$db = db_connect();
	$code_process = new code_process( $db );

	if ( !$code_process->load( 'code_file_name' ,  $request['code_file_name'] ) ){
		
		$_SESSION['fail_message'] = '指定代码不存在.' ;
		$_SESSION['url'] = '';
		header( 'Location: ../message_handle.php' );
		exit ;
	}
	
	echo $result = $code_process->do_judge();
	//返回结果之后,根据返回的结果不同
	//触发一些事件
	$result = json_decode( $result , true );

	$problem_process = new problem_process( $db );
	$problem_process->load( 'problem_no' , $result['problem_no'] ) ;

	//@todo for test
	$username = $_SESSION['username'];
	$user_judge_stat_proc = new user_judge_statistics_process( $db );
	$user_judge_stat_proc->load( 'username' , $username );

	//增加提交次数
	$problem_process->plus_submit_count();
	$user_judge_stat_proc->plus( 'submit_times' );
	
	switch ( $result['result'] ){
	 
		case 'Accepted' :  
			$problem_process->plus_ac_count();
			//更新相关题目的best_user
			$problem_process->update_best_user();

			$user_judge_stat_proc->plus( 'accepted_times' );
			break ;
		case 'Wrong Answer' :
			$user_judge_stat_proc->plus( 'wrong_answer_times' );
			break ;
		case 'Presentation' :
			$user_judge_stat_proc->plus( 'presentation_times' );
			break ;
		case 'Compilation Error' :
			$user_judge_stat_proc->plus( 'compilation_error_times' );
			break;
		case 'Time Exceeded' :
			$user_judge_stat_proc->plus( 'time_exceeded_times' );
			break;
		case 'Memory Exceeded' :
 			$user_judge_stat_proc->plus( 'memory_exceeded_times' );
			break;
		case 'Output Exceeded' :
			$user_judge_stat_proc->plus( 'output_exceeded_times' );
			break;
		case 'Runtime Error' :
			$user_judge_stat_proc->plus( 'runtime_error_times' );
			break;
		case 'Compile Time over' :
			$user_judge_stat_proc->plus( 'compile_time_over' );
			break ;
		default :
			break ; 
	}
	$user_judge_stat_proc->save();
	$problem_process->save();

	//更新judge_result列表
	$result['code_file_name'] = $request['code_file_name'];
	$judge_result_proc = new judge_result_process( $db );
	$judge_result_proc->insert_new_result( $result );

	header( 'Location: ./judge_result.php' );

}catch(Exception $e){

	exception_handle( $e );

}
